"""
这是一个示例大型Python文件，用于演示代码优化器的功能。
该文件包含多个类和函数，适合被拆分成多个模块。
"""

import os
import sys
import time
import json
import logging
from typing import Dict, List, Any, Optional, Tuple, Union
from datetime import datetime, timedelta
import requests
from pathlib import Path

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("app.log")
    ]
)
logger = logging.getLogger(__name__)

# 全局配置
CONFIG = {
    "api_url": "https://api.example.com",
    "timeout": 30,
    "retry_count": 3,
    "cache_dir": ".cache",
    "max_items": 100,
    "debug": False
}

# 工具函数
def load_config(config_path: str) -> Dict[str, Any]:
    """
    从JSON文件加载配置
    
    Args:
        config_path: 配置文件路径
        
    Returns:
        配置字典
    """
    try:
        with open(config_path, 'r') as f:
            return json.load(f)
    except Exception as e:
        logger.error(f"加载配置失败: {e}")
        return {}

def save_config(config: Dict[str, Any], config_path: str) -> bool:
    """
    保存配置到JSON文件
    
    Args:
        config: 配置字典
        config_path: 配置文件路径
        
    Returns:
        是否成功
    """
    try:
        with open(config_path, 'w') as f:
            json.dump(config, f, indent=2)
        return True
    except Exception as e:
        logger.error(f"保存配置失败: {e}")
        return False

def retry_operation(func, max_retries: int = 3, delay: int = 1):
    """
    重试操作的装饰器
    
    Args:
        func: 要重试的函数
        max_retries: 最大重试次数
        delay: 重试延迟（秒）
        
    Returns:
        装饰后的函数
    """
    def wrapper(*args, **kwargs):
        retries = 0
        while retries < max_retries:
            try:
                return func(*args, **kwargs)
            except Exception as e:
                retries += 1
                if retries >= max_retries:
                    raise e
                logger.warning(f"操作失败，正在重试 ({retries}/{max_retries}): {e}")
                time.sleep(delay * retries)  # 指数退避
    return wrapper

def format_timestamp(timestamp: float) -> str:
    """
    格式化时间戳为可读字符串
    
    Args:
        timestamp: Unix时间戳
        
    Returns:
        格式化的时间字符串
    """
    dt = datetime.fromtimestamp(timestamp)
    return dt.strftime("%Y-%m-%d %H:%M:%S")

def ensure_dir(directory: str) -> None:
    """
    确保目录存在，如果不存在则创建
    
    Args:
        directory: 目录路径
    """
    Path(directory).mkdir(parents=True, exist_ok=True)

def calculate_statistics(values: List[float]) -> Dict[str, float]:
    """
    计算统计数据
    
    Args:
        values: 数值列表
        
    Returns:
        包含统计结果的字典
    """
    if not values:
        return {"count": 0, "min": 0, "max": 0, "avg": 0, "sum": 0}
    
    return {
        "count": len(values),
        "min": min(values),
        "max": max(values),
        "avg": sum(values) / len(values),
        "sum": sum(values)
    }

# API客户端类
class ApiClient:
    """API客户端类，用于与远程API交互"""
    
    def __init__(self, base_url: str, timeout: int = 30, api_key: Optional[str] = None):
        """
        初始化API客户端
        
        Args:
            base_url: API基础URL
            timeout: 请求超时时间（秒）
            api_key: API密钥（可选）
        """
        self.base_url = base_url
        self.timeout = timeout
        self.api_key = api_key
        self.session = requests.Session()
        
        if api_key:
            self.session.headers.update({"Authorization": f"Bearer {api_key}"})
    
    def get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        发送GET请求
        
        Args:
            endpoint: API端点
            params: 查询参数
            
        Returns:
            API响应
        """
        url = f"{self.base_url}/{endpoint}"
        response = self.session.get(url, params=params, timeout=self.timeout)
        response.raise_for_status()
        return response.json()
    
    def post(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        发送POST请求
        
        Args:
            endpoint: API端点
            data: 请求数据
            
        Returns:
            API响应
        """
        url = f"{self.base_url}/{endpoint}"
        response = self.session.post(url, json=data, timeout=self.timeout)
        response.raise_for_status()
        return response.json()
    
    def put(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        发送PUT请求
        
        Args:
            endpoint: API端点
            data: 请求数据
            
        Returns:
            API响应
        """
        url = f"{self.base_url}/{endpoint}"
        response = self.session.put(url, json=data, timeout=self.timeout)
        response.raise_for_status()
        return response.json()
    
    def delete(self, endpoint: str) -> Dict[str, Any]:
        """
        发送DELETE请求
        
        Args:
            endpoint: API端点
            
        Returns:
            API响应
        """
        url = f"{self.base_url}/{endpoint}"
        response = self.session.delete(url, timeout=self.timeout)
        response.raise_for_status()
        return response.json()
    
    @retry_operation
    def fetch_with_retry(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        带重试的GET请求
        
        Args:
            endpoint: API端点
            params: 查询参数
            
        Returns:
            API响应
        """
        return self.get(endpoint, params)

# 缓存管理器类
class CacheManager:
    """缓存管理器，用于缓存API响应和其他数据"""
    
    def __init__(self, cache_dir: str, max_age: int = 3600):
        """
        初始化缓存管理器
        
        Args:
            cache_dir: 缓存目录
            max_age: 缓存最大有效期（秒）
        """
        self.cache_dir = cache_dir
        self.max_age = max_age
        ensure_dir(cache_dir)
    
    def _get_cache_path(self, key: str) -> str:
        """
        获取缓存文件路径
        
        Args:
            key: 缓存键
            
        Returns:
            缓存文件路径
        """
        # 使用MD5哈希作为文件名，避免文件名过长或包含非法字符
        import hashlib
        hashed_key = hashlib.md5(key.encode()).hexdigest()
        return os.path.join(self.cache_dir, f"{hashed_key}.json")
    
    def get(self, key: str) -> Optional[Any]:
        """
        获取缓存数据
        
        Args:
            key: 缓存键
            
        Returns:
            缓存数据，如果不存在或已过期则返回None
        """
        cache_path = self._get_cache_path(key)
        
        if not os.path.exists(cache_path):
            return None
        
        try:
            # 检查文件修改时间
            mtime = os.path.getmtime(cache_path)
            if time.time() - mtime > self.max_age:
                # 缓存已过期
                return None
            
            with open(cache_path, 'r') as f:
                cache_data = json.load(f)
                return cache_data.get("data")
        except Exception as e:
            logger.warning(f"读取缓存失败: {e}")
            return None
    
    def set(self, key: str, data: Any) -> bool:
        """
        设置缓存数据
        
        Args:
            key: 缓存键
            data: 要缓存的数据
            
        Returns:
            是否成功
        """
        cache_path = self._get_cache_path(key)
        
        try:
            with open(cache_path, 'w') as f:
                cache_data = {
                    "timestamp": time.time(),
                    "data": data
                }
                json.dump(cache_data, f)
            return True
        except Exception as e:
            logger.warning(f"写入缓存失败: {e}")
            return False
    
    def clear(self, max_age: Optional[int] = None) -> int:
        """
        清除过期缓存
        
        Args:
            max_age: 最大有效期（秒），如果为None则使用默认值
            
        Returns:
            清除的文件数量
        """
        if max_age is None:
            max_age = self.max_age
        
        count = 0
        now = time.time()
        
        for filename in os.listdir(self.cache_dir):
            file_path = os.path.join(self.cache_dir, filename)
            
            if os.path.isfile(file_path) and filename.endswith(".json"):
                mtime = os.path.getmtime(file_path)
                if now - mtime > max_age:
                    try:
                        os.remove(file_path)
                        count += 1
                    except Exception as e:
                        logger.warning(f"删除缓存文件失败: {e}")
        
        return count

# 数据处理器类
class DataProcessor:
    """数据处理器，用于处理和转换数据"""
    
    def __init__(self, config: Dict[str, Any]):
        """
        初始化数据处理器
        
        Args:
            config: 配置字典
        """
        self.config = config
        self.api_client = ApiClient(
            config["api_url"],
            timeout=config["timeout"]
        )
        self.cache = CacheManager(
            config["cache_dir"],
            max_age=config.get("cache_max_age", 3600)
        )
    
    def fetch_data(self, endpoint: str, params: Optional[Dict[str, Any]] = None, use_cache: bool = True) -> Dict[str, Any]:
        """
        获取数据，支持缓存
        
        Args:
            endpoint: API端点
            params: 查询参数
            use_cache: 是否使用缓存
            
        Returns:
            API响应数据
        """
        # 构建缓存键
        cache_key = f"{endpoint}:{json.dumps(params or {})}"
        
        # 尝试从缓存获取
        if use_cache:
            cached_data = self.cache.get(cache_key)
            if cached_data is not None:
                logger.debug(f"从缓存获取数据: {endpoint}")
                return cached_data
        
        # 从API获取
        logger.debug(f"从API获取数据: {endpoint}")
        data = self.api_client.fetch_with_retry(endpoint, params)
        
        # 缓存结果
        if use_cache:
            self.cache.set(cache_key, data)
        
        return data
    
    def process_items(self, items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        处理项目列表
        
        Args:
            items: 项目列表
            
        Returns:
            处理后的项目列表
        """
        result = []
        
        for item in items:
            # 深拷贝，避免修改原始数据
            processed = dict(item)
            
            # 添加处理时间戳
            processed["processed_at"] = time.time()
            
            # 格式化日期字段
            if "created_at" in processed and isinstance(processed["created_at"], (int, float)):
                processed["created_at_formatted"] = format_timestamp(processed["created_at"])
            
            # 计算派生字段
            if "values" in processed and isinstance(processed["values"], list):
                processed["statistics"] = calculate_statistics(processed["values"])
            
            result.append(processed)
        
        return result
    
    def filter_items(self, items: List[Dict[str, Any]], criteria: Dict[str, Any]) -> List[Dict[str, Any]]:
        """
        根据条件过滤项目
        
        Args:
            items: 项目列表
            criteria: 过滤条件
            
        Returns:
            过滤后的项目列表
        """
        result = []
        
        for item in items:
            match = True
            
            for key, value in criteria.items():
                if key not in item or item[key] != value:
                    match = False
                    break
            
            if match:
                result.append(item)
        
        return result
    
    def sort_items(self, items: List[Dict[str, Any]], key: str, reverse: bool = False) -> List[Dict[str, Any]]:
        """
        排序项目
        
        Args:
            items: 项目列表
            key: 排序键
            reverse: 是否降序
            
        Returns:
            排序后的项目列表
        """
        return sorted(items, key=lambda x: x.get(key, 0), reverse=reverse)
    
    def group_items(self, items: List[Dict[str, Any]], key: str) -> Dict[str, List[Dict[str, Any]]]:
        """
        按键分组项目
        
        Args:
            items: 项目列表
            key: 分组键
            
        Returns:
            